package com.sskj.fabi.ui.fragment;


import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bulong.rudeness.RudenessScreenHelper;
import com.shizhefei.mvc.MVCCoolHelper;
import com.shizhefei.view.coolrefreshview.CoolRefreshView;
import com.sskj.common.adapter.slimadapter.IViewInjector;
import com.sskj.common.adapter.slimadapter.SlimAdapter;
import com.sskj.common.adapter.slimadapter.SlimInjector;
import com.sskj.common.base.App;
import com.sskj.common.box.decoration.DividerLineItemDecoration;
import com.sskj.common.rxbus2.RxBus;
import com.sskj.common.rxbus2.Subscribe;
import com.sskj.common.rxbus2.ThreadMode;
import com.sskj.common.util.NumberUtil;
import com.sskj.common.util.SPUtil;
import com.sskj.common.util.ToastUtil;
import com.sskj.fabi.R;
import com.sskj.fabi.R2;
import com.sskj.fabi.bean.FabiListBean;
import com.sskj.fabi.bean.PayWayBean;
import com.sskj.fabi.component.DaggerUserDataComponent;
import com.sskj.fabi.presenter.MarketBuyAndSellFragmentPresenter;
import com.sskj.fabi.util.TipFabiUtil;
import com.sskj.lib.RConfig;
import com.sskj.lib.RxBusCode;
import com.sskj.lib.SPConfig;
import com.sskj.lib.base.BaseFragment;
import com.sskj.lib.bean.UserData;
import com.sskj.lib.model.room.UserViewModel;
import com.sskj.lib.mvchelper.ModelRx2DataSource;
import com.sskj.lib.util.CommonUtil;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import io.reactivex.Flowable;

@Route(path = RConfig.FABI_FRAGMENT_MARKET_BUY_AND_SELL)
public class MarketBuyAndSellFragment extends BaseFragment<MarketBuyAndSellFragmentPresenter> {
    @BindView(R2.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R2.id.coolRefreshView)
    CoolRefreshView coolRefreshView;
    private SlimAdapter slimAdapter;
    @Inject
    UserViewModel userViewModel;
    private UserData userData;
    private MaterialDialog tipOrder;
    private MVCCoolHelper<List<FabiListBean>> mvcHelper;
    FabiListBean data;

    @Override
    protected int getLayoutId() {
        return R.layout.fabi_fragment_market_buy_and_sell;
    }

    @Autowired
    boolean isBuy = false;

    @Override
    public MarketBuyAndSellFragmentPresenter getPresenter() {
        return new MarketBuyAndSellFragmentPresenter();
    }

    @Override
    public void initView() {
        ARouter.getInstance().inject(this);
        RxBus.getDefault().register(this);
        DaggerUserDataComponent.create().inject(this);
        userViewModel.getUsers().observe(this, users -> {
            if (users != null && users.size() > 0) {
                userData = users.get(0);
            } else {
                userData = null;
            }
        });
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.addItemDecoration(new DividerLineItemDecoration(getActivity())
                .setFirstDraw(true)
                .setPaintWidth((int) RudenessScreenHelper.pt2px(App.INSTANCE, 20))
                .setDividerColor(ContextCompat.getColor(App.INSTANCE, R.color.transparent))
        );
        slimAdapter = SlimAdapter.create().register(R.layout.fabi_recy_item_market_buy_and_sell, new SlimInjector<FabiListBean>() {

            @Override
            public void onInject(FabiListBean data, IViewInjector injector, List payloads) {
                String payType = data.getPayType();// 卖家支付方式(1-微信;2-支付宝;3-银行卡)
                String[] result1 = payType.split(",");
                for (int i = 0; i < result1.length; i++) {
                    if (result1[i].equals("1")) {
                        data.setPay_wx("1");
                    } else if (result1[i].equals("2")) {
                        data.setPay_alipay("1");
                    } else if (result1[i].equals("3")) {
                        data.setPay_backcard("1");
                    }
                }
                String tradeNum = new BigDecimal(data.getDealsNum()).subtract(new BigDecimal(data.getTransNum())).toPlainString();
                String percent = CommonUtil.dealCNY(new BigDecimal(tradeNum).multiply(new BigDecimal(100)).divide(new BigDecimal(data.getDealsNum()), 4, RoundingMode.HALF_UP).toPlainString());
                injector
                        .text(R.id.tvNameIcon, data.getRealname().charAt(0) + "")
                        .text(R.id.tvName, data.getRealname().charAt(0) + "**")
                        .text(R.id.tvLimit, data.getLimitNum())
                        .text(R.id.tvPercent, String.format("成交笔数%s | %s", tradeNum, percent) + "%")
                        .text(R.id.tvMoney, data.getPrice() + " CNY")
                        .text(R.id.tvNum, String.format("数量 %s USDT", CommonUtil.dealCoin(data.getDealsNum())))
                        .text(R.id.btSubmit, isBuy ? "购买" : "出售")
                        .visibility(R.id.viewAL, data.getPay_alipay().equals("1") ? View.VISIBLE : View.GONE)
                        .visibility(R.id.viewWX, data.getPay_wx().equals("1") ? View.VISIBLE : View.GONE)
                        .visibility(R.id.viewYL, data.getPay_backcard().equals("1") ? View.VISIBLE : View.GONE)
                        .background(R.id.btSubmit, ContextCompat.getDrawable(App.INSTANCE, isBuy ? R.drawable.fabi_shape_corner4_f53 : R.drawable.fabi_shape_corner4_05c))
                        .clicked(R.id.btSubmit, v -> {
                            if (userData == null) {
                                ToastUtil.showShort("请先登录");
                                return;
                            }
                            if (SPUtil.get(SPConfig.ID, "").equals(data.getStockUserId())) {
                                ToastUtil.showShort("自己的单子，不能交易");
                                return;
                            }
                            if (isBuy) {
                                tipOrder = TipFabiUtil.showBuy(getActivity(), isBuy, data.getPrice(),
                                        data.getMinPrice(), data.getMaxPrice(), data.getDealsNum(),
                                        userData.getUsableFund(), null, (payPwd, num, money, payTypes) -> {
                                            mPresenter.order(payPwd, data.getOrder_no(), num, money, isBuy, null);
                                        });
                            } else {
                                MarketBuyAndSellFragment.this.data = data;
                                mPresenter.requsetPayWayList();
                            }
                        });
            }
        });
        slimAdapter.attachTo(recyclerView).updateData(new ArrayList());
        ModelRx2DataSource<FabiListBean> dataSource = new ModelRx2DataSource<>((ModelRx2DataSource.OnLoadSource<FabiListBean>)
                page -> mPresenter.getFabiList(page, 20, isBuy), 20);
        mvcHelper = new MVCCoolHelper<>(coolRefreshView);
        mvcHelper.setDataSource(dataSource);
        mvcHelper.setAdapter(slimAdapter);
        mvcHelper.refresh();
    }


    public void orderSuccess() {
        if (tipOrder != null && tipOrder.isShowing()) {
            tipOrder.dismiss();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, code = RxBusCode.FABI_DATING_REFRESH)
    public void refresh() {
        if (mvcHelper != null) {
            mvcHelper.refresh();
        }
    }

    public void onPayWaySuccess(List<PayWayBean> payWayBeanList) {
        tipOrder = TipFabiUtil.showBuy(getActivity(), isBuy, data.getPrice(),
                data.getMinPrice(), data.getMaxPrice(), data.getDealsNum(),
                userData.getUsableFund(), payWayBeanList, (payPwd, num, money, payType) -> {
                    mPresenter.order(payPwd, data.getOrder_no(), num, money, isBuy, payType);
                });
    }
}
